type BusClass = {
  emit: (name: string) => void
  on: (name: string, callback: Function) => void
}
type paramsKey = string | number | symbol
type listType = {
  [key: paramsKey]: Array<Function>
}

class Bus implements BusClass {
  list:listType
  constructor() {
    this.list = {}
  }
  emit(name: string, ...args: Array<any>) {
    let eventName: Array<Function> = this.list[name] // 取到on注册的callback集合
    eventName.forEach(fn => {
      // 调用函数需要使用apply,把 emit 里面的参数传给 on 里面的callback
      fn.apply(this, args)
    })
  }
  on(name: string, callback: Function) {
    // fn的类型是函数数组的原因：on方法可以被多次注册
    let fn: Array<Function> = this.list[name] || []
    fn.push(callback)
    this.list[name] = fn
  }
}

export default new Bus()